package com.iszhouhua.blog.common.interceptor;

import com.aliyun.oss.HttpMethod;
import com.iszhouhua.blog.common.constant.Const;
import com.iszhouhua.blog.common.util.Result;
import com.iszhouhua.blog.controller.vue.UserController;
import com.iszhouhua.blog.model.User;
import com.iszhouhua.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookiendSessionInterceptor implements HandlerInterceptor {
  @Autowired
  private UserService userService;

  @Autowired
  private RedisTemplate redisTemplate;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // 如果不是映射到方法直接通过
    if (!(handler instanceof HandlerMethod)) {
      return true;
    }
     //如果是 OPTIONS 请求，让 OPTIONS 请求返回一个200状态码
//    if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
//      response.setStatus(HttpServletResponse.SC_OK);
//      return false;
//    }
//    if(request.getMethod().toUpperCase().equals("OPTIONS")){
//      return true;//通过所有OPTION请求
//    }
    String token = request.getHeader(Const.USER_SESSION_KEY);
    System.out.println("token============"+token);
    if (token != null){
      Object user = redisTemplate.opsForValue().get(token);
      if (!StringUtils.isEmpty(user)){
        return true;
      }
    }
    //返回false，不执行原来controller的方法
    //否则进行拦截
    return false;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  }
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  }
}
